<?php


namespace app\service;

use app\model\Products;

class ProductsService
{
    protected $productModel;

    public function __construct()
    {
        $this->productModel = new Products();
    }
    public function getHotRecommend()
    {
        // 随机获取回来10个
        $list= $this->productModel->where(['active'=>1,'approved_status'=>1])
        ->order('position_seller','asc')
        ->order('id','desc')
        ->limit(10)
        ->with(['defaultSku','description'])
        ->field('id,images')
        ->select()
        ->toArray();
        foreach($list as &$item){
            
            $item['image']=$item['images']?(env('IMAGE_URL').$item['images'][0]):'';
            
            $item['price']=empty($item['defaultSku'])?$item['price']: floatval($item['defaultSku']['price']);
            $item['name'] = empty($item['description'])?'':$item['description']['name'];
        }
        return $list;
    }

     public function getSearchProduct($query)
    {
        $page = $query->get('page',1);
        $limit = $query->get('limit',10);
        $keyword = $query->get('keyword','');
        $page = ($page-1)*$limit;
        $where = [
            ['p.active','=',1],
            ['p.approved_status','=',1],
        ];
        if($keyword){
            $where[]=['d.name','like','%'.$keyword.'%'];
        }
        // 随机获取回来10个
        $list= $this->productModel->alias('p')
        ->leftJoin('product_descriptions d','p.id=d.product_id')
        ->leftJoin('sellers s','p.seller_id=s.id')
        ->where($where)
        ->order('p.position_seller','asc')
        ->order('p.id','desc')
        ->field('p.*,d.name,s.id as seller_id,s.store_name')
        ->limit($page,$limit)
        ->with(['defaultSku'])
        ->select()
        ->toArray();
        foreach($list as &$item){
            $item['image']=$item['images']?(env('IMAGE_URL').$item['images'][0]):'';
            $item['price']=empty($item['defaultSku'])?$item['price']: floatval($item['defaultSku']['price']);
            // $item['name'] = empty($item['description'])?'':$item['description']['name'];
        }
        return $list;
    }
}